﻿using Atletika.Shared.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Atletika.Shared.Helpers
{
    public static class DownloadHelper
    {
        public const string baseAdress = "http://www.atletikasvk.sk/";
        public const string atlbaseAdress = "http://www.atletis.sk/";

        #region Articles

        public async static Task<List<Article>> GetArticles()
        {
            DateTime start = DateTime.Now;

            HttpClient client = new HttpClient();

            string jsonText = await client.GetStringAsync(baseAdress + "DataOutput/ArticlesLight?count=100");

            Debug.WriteLine(string.Format("Articles downloaded: {0} ms", (DateTime.Now - start).TotalMilliseconds));

            List<Article> articles = new List<Article>();
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonText));
            DataContractJsonSerializer ser = new DataContractJsonSerializer(articles.GetType());
            articles = ser.ReadObject(ms) as List<Article>;

            Debug.WriteLine(string.Format("Articles serialized: {0} ms", (DateTime.Now - start).TotalMilliseconds));

            articles.FirstOrDefault(a => a.CategoryId == 1).Top = true;
            articles.FirstOrDefault(a => a.CategoryId == 2).Top = true;

            var ts = DateTime.UtcNow - DateTime.Now;

            foreach (var a in articles)
            {
                a.Date = a.Date.AddSeconds(-ts.TotalSeconds);
            }

            return articles;
        }

        public async static Task<Article> GetArticleById(int id)
        {
            HttpClient client = new HttpClient();

            string jsonText = await client.GetStringAsync(baseAdress + "DataOutput/ArticleById/" + id.ToString());

            Article article = new Article();
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonText));
            DataContractJsonSerializer ser = new DataContractJsonSerializer(article.GetType());
            article = ser.ReadObject(ms) as Article;

            var ts = DateTime.UtcNow - DateTime.Now;
            article.Date = article.Date.AddSeconds(-ts.TotalSeconds);
            article.Text = FormatHtml(article.Text);

            return article;
        }

        private static string FormatHtml(string text)
        {
            text = text.Replace("</p>", Environment.NewLine);
            text = text.Replace("<br>", Environment.NewLine);
            text = text.Replace("<br/>", Environment.NewLine);
            text = text.Replace("<br />", Environment.NewLine);
            text = Regex.Replace(text, @"<[^>]*>", String.Empty);
            
            text = WebUtility.HtmlDecode(text);
            
            return text;
        }

        #endregion

        #region Competitions

        public async static Task<List<Competition>> GetCompetitions()
        {
            DateTime start = DateTime.Now;

            HttpClient client = new HttpClient();

            string jsonText = await client.GetStringAsync(baseAdress + "DataOutput/Competitions");

            Debug.WriteLine(string.Format("Competitions downloaded: {0} ms", (DateTime.Now - start).TotalMilliseconds));

            List<Competition> competitions = new List<Competition>();
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonText));
            DataContractJsonSerializer ser = new DataContractJsonSerializer(competitions.GetType());
            competitions = ser.ReadObject(ms) as List<Competition>;

            Debug.WriteLine(string.Format("Competitions serialized: {0} ms", (DateTime.Now - start).TotalMilliseconds));

            var ts = DateTime.UtcNow - DateTime.Now;

            foreach (var c in competitions)
            {
                c.DateFrom = c.DateFrom.AddSeconds(-ts.TotalSeconds);
            }

            return competitions;
        }

        public async static Task<List<Competition>> GetCompetitionsByYearAndMonth(int year, int month)
        {
            DateTime start = DateTime.Now;

            HttpClient client = new HttpClient();

            string jsonText = await client.GetStringAsync(baseAdress + string.Format("DataOutput/CompetitionsByYearAndMonth?year={0}&month={1}", year, month));

            Debug.WriteLine(string.Format("Competitions downloaded: {0} ms", (DateTime.Now - start).TotalMilliseconds));

            List<Competition> competitions = new List<Competition>();
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonText));
            DataContractJsonSerializer ser = new DataContractJsonSerializer(competitions.GetType());
            competitions = ser.ReadObject(ms) as List<Competition>;

            Debug.WriteLine(string.Format("Competitions serialized: {0} ms", (DateTime.Now - start).TotalMilliseconds));

            var ts = DateTime.UtcNow - DateTime.Now;

            foreach (var c in competitions)
            {
                c.DateFrom = c.DateFrom.AddSeconds(-ts.TotalSeconds);
            }

            return competitions;
        }

        #endregion

        #region DisciplineList

        public async static Task<List<DisciplineList>> GetDisciplineList(int competitionId)
        {
            HttpClient client = new HttpClient();

            string jsonText = await client.GetStringAsync("http://atletis.sk/DataOutput/DisciplineList?competitionId=" + competitionId.ToString());

            List<DisciplineList> disciplineList = new List<DisciplineList>();
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonText));
            DataContractJsonSerializer ser = new DataContractJsonSerializer(disciplineList.GetType());
            disciplineList = ser.ReadObject(ms) as List<DisciplineList>;

            return disciplineList;


        }

        #endregion

    }
}
